#include <stdio.h>
#include "modbus.h"
#include <cJSON.h>
#include <msg_queue.h>
#include <shmem.h>
#include <msg_queue_peer.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

struct msgbuf
{
	long mtype;
	char mdata[256];
};
union val_t
{ 
    int b_val;  //bool类型存储空间
    int i_val;   //整形值存储空间
    float f_val;  //浮点值存储空间
};

struct std_node
{
	int key;  //唯一键值
	int type;  //数据点类型
    int dev_type;  //属于哪个设备：m0或modbus或者手机APP
	union val_t old_val;  //变化上报后需要更新旧值
    union val_t new_val;  //从共享内存取出最新数据，放到new_val中
    int ret;  //默认为-1，采集成功后设置为0，采集失败再置-1
};
int main(int argc, const char *argv[])
{
	struct msgbuf send_msg_buf;
	send_msg_buf.mtype = 1L;
	struct msgbuf recv_msg_buf;

     //序列化************************************************************************
    cJSON *root = cJSON_CreateObject();
    if (!root)
    {
        printf("create root err.");
        return -1;
    }
 
    cJSON *ver = cJSON_CreateNumber(2);
    cJSON_AddItemToObject(root, "type", ver);
    cJSON *data = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "data", data);
	cJSON *ver_1 = cJSON_CreateNumber(1);
    cJSON_AddItemToObject(data, "key", ver_1);
	cJSON *ver_2 = cJSON_CreateString("1");
    cJSON_AddItemToObject(data, "val", ver_2);

	//char *p = fgets(send_msg_buf.mdata, 256, stdin);
    printf("%s\n",cJSON_Print(root));
	sprintf(send_msg_buf.mdata, "%s", cJSON_Print(root));
	if(msg_queue_send("msgn", &send_msg_buf, sizeof(send_msg_buf), 1L) < 0)
	{
		printf("msg_queue_send error\n");
		return -1;
	}
	if(msg_queue_recv("msgn", &recv_msg_buf, sizeof(recv_msg_buf), 2L, 0) > 0)
	{
		//从缓冲区中解析出JSON结构                                   
		root = cJSON_Parse(recv_msg_buf.mdata);//得到总节点
		//bzero(recv_buf.mdata,sizeof(recv_buf.mdata));
		cJSON *item = cJSON_GetObjectItem(root, "msg");

		printf("recv from msga type = %s\n", item->valuestring);
		
	}
	else
	{
		perror("recv error:");
		//break;
	}
   //创建共享内存*********************************************************************
static struct shm_param para;
	//共享内存初始化
	int ret = shm_init(&para, "shm_test", 1024);
	if(ret < 0)
	{
		perror("共享内存初始化失败.");
		return -1;
	}
	//得到共享内存空间地址
	struct std_node *addr = shm_getaddr(&para);
	if(addr == NULL)
	{
		perror("get shem addr err.\n");
		return -1;
	}
while(1)
{   
	sleep(1);
	printf("%d\n",addr[0].new_val.i_val);
	printf("X:%.2f\n",addr[1].new_val.f_val);
    printf("Y:%.2f\n",addr[2].new_val.f_val);
    printf("Z:%.2f\n",addr[3].new_val.f_val);
	printf("X:%.2f\n",addr[1].old_val.f_val);
    printf("Y:%.2f\n",addr[2].old_val.f_val);
    printf("Z:%.2f\n",addr[3].old_val.f_val);

}
	shm_del(&para);
	cJSON_Delete(root);
     	return 0;
}
